﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Model;
using Model.viewModel;
using Microsoft.EntityFrameworkCore;
using Dal.Iterfease;

namespace Dal.infDal
{
    public class CartDal : ICartDal
    {
        private readonly AppDbContext _appDbContext;

        public CartDal(AppDbContext appDbContext)
        {
            _appDbContext = appDbContext;
        }

        /// <summary>
        /// 购物车添加
        /// </summary>
        /// <param name="cart"></param>
        /// <returns></returns>
        public int AddCart(shoppingCart cart)
        {
            var a = _appDbContext.shoppingCart.FirstOrDefault(u => u.SMid == cart.SMid && u.Suid == cart.Suid);
            if (a != null)
            {
                a.Ssum += cart.Ssum;
            }
            else
            {
                _appDbContext.shoppingCart.Add(cart);
            }

            return _appDbContext.SaveChanges();
        }

        /// <summary>
        /// 购物车显示
        /// </summary>
        /// <param name="Uid"></param>
        /// <returns></returns>
        public List<CommodModel> showCart(int Uid,out int couetsumb)
        {
            var sql = from a in _appDbContext.commodityInfos
                      join b in _appDbContext.shoppingCart on a.Cid equals b.SMid
                      where Uid == b.Suid
                      select new CommodModel
                      {
                          Cid = a.Cid,
                          Scid = b.Scid,
                          Cname = a.Cname,
                          Cprice = a.Cprice,
                          Cversions = a.Cversions,
                          Cimg = "http://localhost:16673/StaticFiles/" + a.Cimg,
                          Ssum = b.Ssum,
                      };
            couetsumb = 0;
            foreach (var item in sql)
            {
                couetsumb += item.Ssum;
            }

            return sql.ToList();
        }


        /// <summary>
        /// 购物车商品删除
        /// </summary>
        /// <param name="Scid"></param>
        /// <returns></returns>
        public int delCart(int Scid)
        {
            var a=_appDbContext.shoppingCart.FirstOrDefault(u => u.Scid == Scid);
            _appDbContext.Remove(a);
            return _appDbContext.SaveChanges();
        }

        /// <summary>
        /// 数量同步
        /// </summary>
        /// <param name="sid"></param>
        /// <param name="num"></param>
        /// <returns></returns>
        public int UpShoppingCarNum(int Scid, int Ssum)
        {
            var arr = _appDbContext.shoppingCart.FirstOrDefault(m => m.Scid == Scid);
            arr.Ssum = Ssum;
            return _appDbContext.SaveChanges();
        }
    }
}
